package com.yishu.shop.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yishu.shop.service.UserService;
import com.ys.commons.constant.ResponseCode;
import com.ys.commons.exception.YsException;
import com.ys.commons.model.JsonResponse;
import com.ys.commons.model.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 商城用户接口
 *
 * @author zengchao
 * @date 2021-07-07 20:33:25
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserService userService;

    @GetMapping()
    public JsonResponse<UserDto> getUserInfo(@RequestParam("id")Integer id){
        try {
            String body = restTemplate.getForObject("http://user-server/user?id={id}", String.class, id);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonResponse<UserDto> jsonResponse = objectMapper.readValue(body, new TypeReference<JsonResponse<UserDto>>() {
            });
            if (!ResponseCode.OK.getCode().equals(jsonResponse.getCode())){
                throw new YsException(String.format("错误的响应码:[%s]",body));
            }
            return jsonResponse;
        } catch (Exception e) {
            log.error("调用user-server失败!",e);
        }
        return JsonResponse.error("获取用户信息失败",null);
    }

    @GetMapping("feign")
    public JsonResponse<UserDto> getUserInfo2(@RequestParam("id")Integer id){
        JsonResponse<UserDto> jsonResponse = userService.getUser(id);
        if (!ResponseCode.OK.getCode().equals(jsonResponse.getCode())){
            throw new YsException(String.format("错误的响应码:[%s]",jsonResponse));
        }
        return jsonResponse;
    }

}
